/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package frame;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import kbcquiz.App;
import library.DB;
import library.Utils;

public class AdminUser extends javax.swing.JFrame {

    private boolean EditMode = false;
    private AdminModel data;
    
    public AdminUser() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tfUser = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        btnSave = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        tfPass = new javax.swing.JPasswordField();
        tfConfirm = new javax.swing.JPasswordField();

        jLabel3.setText("jLabel3");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Username :");

        jLabel2.setText("Password :");

        jLabel4.setText("Confirm password :");

        jLabel5.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(255, 0, 0));
        jLabel5.setText("* Please password blank if you don't to update password");

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnReset.setText("Reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel5)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(btnSave)
                        .addGap(29, 29, 29)
                        .addComponent(btnReset)
                        .addGap(32, 32, 32)
                        .addComponent(btnCancel))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4)
                            .addComponent(jLabel1))
                        .addGap(22, 22, 22)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(tfUser)
                            .addComponent(tfPass, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(tfConfirm, javax.swing.GroupLayout.Alignment.LEADING))
                        .addGap(8, 8, 8)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tfUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tfPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(tfConfirm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel5)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnReset)
                    .addComponent(btnCancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
         if (tfUser.getText().trim().equals("")) {
            Utils.Alert("User name cant be leave blank");
            tfUser.requestFocus();
            return;
        }
        String username = tfUser.getText().trim();
        if (!this.EditMode) {
            try {
                PreparedStatement sm = DB.getConnection().prepareStatement("SELECT * FROM Admins WHERE Username = ?");
                sm.setString(1, username);
                ResultSet rs = sm.executeQuery();
                if (rs.next()) {
                    rs.close();
                    Utils.Alert("This user name is already exist");
                    tfUser.requestFocus();
                    return;
                }
            }
            catch (SQLException ex) {
                Logger.getLogger(AdminUser.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else if(!username.equals(data.getName())){
            try {
                PreparedStatement sm = DB.getConnection().prepareStatement("SELECT * FROM Admins WHERE Username = ? AND ID != ?");
                sm.setString(1, username);
                sm.setInt(2, data.getID());
                ResultSet rs = sm.executeQuery();
                if (rs.next()) {
                    rs.close();
                    Utils.Alert("This user name is already exist");
                    tfUser.requestFocus();
                    return;
                }
            }
            catch (SQLException ex) {
                Logger.getLogger(AdminUser.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        if (this.EditMode) {
            data.setName(username);
        }
        String newPass = "";
        if (!tfPass.getText().trim().equals("")) {
            if (!tfPass.getText().trim().equals(tfConfirm.getText().trim())) {
                Utils.Alert("Password and confirm password does not match");
                tfPass.requestFocus();
                return;
            }
            newPass = tfPass.getText();
            if (this.EditMode) {
                data.setPass(newPass);
            }
        }

        if (!this.EditMode && newPass.equals("")) {
            Utils.Alert("You must enter a password");
            tfPass.requestFocus();
            return;
        }

        if (!this.EditMode) {
            data = new AdminModel(username, newPass);
        }
        if(data.save() != 1){
            Utils.Alert("There is a problem when saving the data, please try again");
            return;
        }
        else{
            Utils.Alert("Saved data into database successfully");
            App.getAdminFrame().reloadAdminData();
            App.switchDisplay("admin");
        }
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
         this.resetData();
    }//GEN-LAST:event_btnResetActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        App.switchDisplay(App.getAdminFrame());
    }//GEN-LAST:event_btnCancelActionPerformed

    public void setEditMode(boolean isedit) {
        this.EditMode = isedit;
        resetData();
    }
    
     public void resetData() {
        if (this.EditMode) {
            if (data != null) {
                this.tfUser.setText(data.getName());
                this.tfPass.setText("");
                this.tfConfirm.setText("");
                this.setTitle("Edit Admin ID: " + data.getID());
            }
            else {
                this.EditMode = false;
                resetData();
            }
        }
        else {
            this.tfUser.setText("");
            this.tfPass.setText("");
            this.tfConfirm.setText("");
            this.setTitle("Add new Admin");
        }
    }
     
      public void loadData(AdminModel model) {
        this.data = model;
        this.setEditMode(true);
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AdminUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AdminUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AdminUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AdminUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new AdminUser().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnSave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPasswordField tfConfirm;
    private javax.swing.JPasswordField tfPass;
    private javax.swing.JTextField tfUser;
    // End of variables declaration//GEN-END:variables
}
